package org.example.config.mqtt;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.collection.Map;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.example.config.mqtt.property.MqttMsgContent;
import org.example.exceptions.BusinessException;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.GenericMessage;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class JsonPahoMessageConverter extends DefaultPahoMessageConverter {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Message<?> toMessage(String topic, MqttMessage mqttMessage) {
        try {
            MqttMsgContent<?> mqttMsgContent = objectMapper.readValue(mqttMessage.getPayload(), MqttMsgContent.class);
            return MessageBuilder
                    .withPayload(mqttMsgContent.getPayload())
                    .copyHeadersIfAbsent(mqttMsgContent.getHeaders())
                    .build();
        } catch (IOException e) {
            throw new RuntimeException("Failed to convert JSON to MQTT message", e);
        }
    }


    @Override
    public MqttMessage fromMessage(Message<?> message, Class<?> targetClass) {
        try {
            // 将字节数组解码为 JSON 字符串并反序列化为对象

            MqttMessage mqttMessage = super.fromMessage(message, targetClass);
            return mqttMessage;
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert MQTT message to JSON", e);
        }
    }
}
